﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.XPath;
using System.Web.UI.WebControls;
using Anthony.Library.Entensions;

namespace Formsy.Web.Settings
{
    public class PrevalueHelper
    {
        /// <summary>
        /// Calls GetListFromXml to get a list of strings, then creates and returns a list of ListItem. 
        /// </summary>
        /// <param name="xmlPath"></param>
        /// <param name="xPathExpression"></param>
        /// <param name="ddl"></param>
        /// <returns></returns>
        public static DropDownList LoadDropDown(string xmlPath, string xPathExpression, DropDownList ddl)
        {
            // Get the list of strings
            List<string> list = GetListFromXml(xmlPath, xPathExpression);

            // Create the ListItems
            List<ListItem> items = new List<ListItem>();
            list.ForEach(x => items.Add(new ListItem(x, x)));

            // Assign and return
            ddl.DataSource = items;
            return ddl;
        }


        /// <summary>
        /// Parses comma delimited input string, then creates dropdown list items.
        /// </summary>
        /// <param name="sItems"></param>
        /// <param name="ddl"></param>
        public static DropDownList LoadDropDown(string sItems, DropDownList ddl)
        {
            string[] ddlItems = sItems.RemoveLineBreaks().Split(",".ToCharArray())
                                    .Select(x => x.Trim()).ToArray();
            List<ListItem> items = new List<ListItem>();
            foreach (string s in ddlItems)
            {
                items.Add(new ListItem(s, s));
            }
            ddl.DataSource = items;

            return ddl;
        }



        /// <summary>
        /// Uses xpath to parse an xml file and returns back a List<string>.
        /// </summary>
        /// <param name="xmlPath"></param>
        /// <param name="xPathExpression"></param>
        /// <returns></returns>
        public static List<string> GetListFromXml(string xmlPath, string xPathExpression)
        {
            // Open the XML.
            XPathDocument docNav = new XPathDocument(HttpContext.Current.Server.MapPath(xmlPath));

            // Create a navigator to query with XPath.
            XPathNavigator nav = docNav.CreateNavigator();

            var nodeIter = nav.Select(xPathExpression);

            List<string> values = new List<string>();
            while (nodeIter.MoveNext())
            {
                string item = nodeIter.Current.Value;
                values.Add(item);
            }

            return values;
        }




    }
}
